import pymysql

# 定义游标变量
cursor = None
conn = None

try:
    # 2.创建数据库连接
    conn = pymysql.connect(host="211.103.136.244", port=7061, user="student", passwd="iHRM_student_2021",
                    database="test_db", charset="utf8")

    # 3.获取游标
    cursor = conn.cursor()

    # 4.查询数据
    # ①：查询t_book表的全部字段数据
    sql_select = "select * from t_book"
    cursor.execute(sql_select)

    # ②：获取查询结果集的第一条数据
    res1 = cursor.fetchone()
    print("获取查询结果集的第一条数据:", res1)

    # ③：获取查询结果集的第3条和第4条数据
    cursor.rownumber = 2
    res2 = cursor.fetchmany(2)
    print("获取查询结果集的第3条和第4条数据:", res2)

    # ④：获取全部的查询结果集及总记录数
    cursor.rownumber = 0
    res3 = cursor.fetchall()
    print("获取全部的查询结果集:", res3)
    print("全部的结果集长度：", len(res3))
except Exception as e:
    print("数据库查询错误：", e)
finally:
    # 5.关闭游标
    if cursor is not None:
        cursor.close()

    # 6.关闭数据库连接
    if conn is not None:
        conn.close()


